package io.mqttpush.mqttserver.msgs;

import io.mqttpush.common.events.CommonTopics;
import io.mqttpush.mqttserver.config.DeviceManager;
import io.mqttpush.mqttserver.config.TopicManager;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author tianzhenjiu
 * @date 2020/4/27 16:45
 */
public class MessageRoute {


    protected Logger logger = LoggerFactory.getLogger(getClass());

    static MessageRoute messageRoute=new MessageRoute();


    public  static  MessageRoute getInstance(){
        return messageRoute;
    }


    public Collection<Channel> routeTopic(String topic){



        HashSet<Channel> routedChannels=new HashSet<>();

        if(topic.startsWith(CommonTopics.ONE_2ONE_PREFIX)){

            int index=topic.lastIndexOf("/");
            String deviceId=null;
            if(index>0&&index<topic.length()-1){
                 deviceId=topic.substring(index+1);
            }

            if(deviceId!=null){
                Channel channel= DeviceManager.getDeviceManager().deviceChannel(deviceId);
                if(channel != null&&channel.isActive()){
                    /**
                     *
                     * 部分mqtt客户端不支持EXACTLY_ONCE
                     */
                    routedChannels.add(channel);
                }
            }

        }


        Set<Channel> channels= TopicManager.getInstance().topicChannels(topic);
        if(channels!=null&&!channels.isEmpty()){
            routedChannels.addAll(channels);
        }
        logger.info("the topic {}   channel's is {}",topic,routedChannels);
        return routedChannels;

    }
}
